package com.breeze.components.mail.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.template.Template;
import cn.hutool.extra.template.TemplateConfig;
import cn.hutool.extra.template.TemplateUtil;
import jakarta.annotation.Resource;
import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import jakarta.validation.constraints.NotNull;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;

/**
 * 发送邮件
 *
 * @author breeze
 */
public class MailExtendService {

  @Resource JavaMailSender javaMailSender;

  @Value("${spring.mail.username}")
  String username;

  public void sendHtmlMail(List<String> to, String subject, String tplPath, Map<?, ?> args)
      throws MessagingException {
    Template template =
        TemplateUtil.createEngine(
                new TemplateConfig(StrUtil.EMPTY, TemplateConfig.ResourceMode.CLASSPATH))
            .getTemplate(tplPath);
    MimeMessage mimeMessage = javaMailSender.createMimeMessage();
    MimeMessageHelper message = new MimeMessageHelper(mimeMessage, false);
    message.setFrom(username);
    message.setTo(to.toArray(new String[0]));
    message.setSentDate(new Date());
    message.setSubject(subject);
    message.setText(template.render(args), true);
    javaMailSender.send(mimeMessage);
  }

  public void sendHtmlMail(
      @NotNull List<String> to,
      String replyTo,
      List<String> cc,
      List<String> bcc,
      @NotNull Date sentDate,
      String subject,
      String content) {

    SimpleMailMessage message = new SimpleMailMessage();
    message.setFrom(username);
    // 回复
    message.setReplyTo(replyTo);

    message.setTo(to.toArray(new String[0]));
    // 抄送
    if (CollUtil.isNotEmpty(cc)) {
      message.setCc(cc.toArray(new String[0]));
    }
    // 暗抄送
    if (CollUtil.isNotEmpty(bcc)) {
      message.setBcc(bcc.toArray(new String[0]));
    }

    message.setSentDate(sentDate);
    message.setSubject(subject);
    message.setText(content);
    javaMailSender.send(message);
  }
}
